#!/usr/bin/env python
import Image
import sys
import os 


def getbcolor(rr, ra, fr, fa, ba):
    """get background color r,g,b"""
    rr = float(rr) / 255
    ra = float(ra) / 255
    fr = float(fr) / 255
    fa = float(fa) / 255
    ba = float(ba) / 255
    if fa == 1 or ba==0:
        return 0
    try:
        br = (rr * ra - fr * fa) / (ba * (1 - fa))
    except Exception, e:
        print fa
        print ba
        print ra
        print ba
    return int(round(br * 255))


def getbalpha(ra, fa):

    fa = float(fa) / 255
    ra = float(ra) / 255
    ba = 1 - (1 - ra) / (1 - fa)
    return int(round(ba*255))


def getmask(im,pix):
    count=[]
    atx=[]
    for i in range(im.size[0]/2):
        if len(count)>30*(im.size[0]/128):
            break
        for j in range(im.size[0]/20, im.size[0]/2):
            (r,g,b,a)=pix[i,j]
            if r==68 and g==68 and b==64:
                if a<=31 and a>=15:
                    count.append(a)
    a=max(count) if len(count)>0 else 31
    if a>15 and a<31:
        a=31
    size=im.size[0]
    filename = 'mask/{}-{}.png' . format(a, size) 
    filename = os.path.dirname(__file__)+'/'+filename
    # print filename
    # print count
    return filename

def main(filename):
    if not os.path.isfile(filename):
        print 'invalid file'
        sys.exit()
    im = Image.open(filename)
    if im.size[0]<128:
        print 'invalid image size, 128x128 at least'
        sys.exit()
    if im.mode!='RGBA':
        print 'invalid image format '. format(im.mode)
        sys.exit()
    pix = im.load()
    im_ = Image.open(getmask(im,pix))
    pix_ = im_.load()
    for i in range(im.size[0]):
        for j in range(im.size[1]):
            if pix[i, j] == pix_[i, j]:
                pix[i, j] = (0, 0, 0, 0)
            elif pix_[i, j] != (0, 0, 0, 0):
                ba = getbalpha(pix[i, j][3], pix_[i, j][3])
                r = getbcolor(pix[i, j][0], pix[i, j][3], pix_[i, j][0], pix_[i, j][3], ba)
                g = getbcolor(pix[i, j][1], pix[i, j][3], pix_[i, j][1], pix_[i, j][3], ba)
                b = getbcolor(pix[i, j][2], pix[i, j][3], pix_[i, j][2], pix_[i, j][3], ba)
                pix[i,j]=(r,g,b,ba)
    newfile=filename.replace('.png','_new.png')
    im.save(newfile)
    print 'new file {} has been generated' . format(newfile)
    # im.show()

if __name__ == '__main__':
    main(sys.argv[1])
